package cn.yujiago.springboot.realm;

import javax.annotation.Resource;

import cn.yujiago.springboot.entity.UserDO;
import cn.yujiago.springboot.exception.CustomAuthenticationException;
import cn.yujiago.springboot.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class PhoneRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        PhoneToken token = null;

        if(authenticationToken instanceof PhoneToken){
            token = (PhoneToken) authenticationToken;
        }else{
            return null;
        }

        String phone = (String) token.getPrincipal();

        UserDO user = userService.selectByPhone(phone);

        if (user == null) {
            throw new CustomAuthenticationException("手机号错误");
        }
        return new SimpleAuthenticationInfo(user, phone, this.getName());
    }

    @Override
    public boolean supports(AuthenticationToken var1){
        return var1 instanceof PhoneToken;
    }
}
